home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 195 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.3 KB

  1. Path: mips.complang.tuwien.ac.at!schwarz
  2. From: schwarz@mips.complang.tuwien.ac.at (Konrad Schwarz)
  3. Newsgroups: comp.std.c
  4. Subject: integral types in switch expressions
  5. Date: 26 Jan 1996 18:17:05 GMT
  6. Organization: TU Wien
  7. Sender: schwarz@a3.complang.tuwien.ac.at (Konrad Schwarz)
  8. Message-ID: <4eb5r1$b04@news.tuwien.ac.at>
  9. NNTP-Posting-Host: a3.complang.tuwien.ac.at
  10.  
  11. I was surprised to learn that constant pointer expressions are
  12. not allowed in case labels and that the expression in a switch statement
  13. must be an integral type.  (The reason for the exclusion of floating point
  14. is obvious to me).  I am interested in the technical reasons for this.
  15.  
  16. Consider:
  17.  
  18. T a [] = { ... }, *b = a + sizeof a / sizeof *a, *c;
  19.  
  20. switch (c) {
  21.     case a: ...
  22.     case a + 1: ...
  23.         case a + 3: ...
  24.     default: ...
  25. }
  26.  
  27. where T is some type.
  28. The assignment to b has worked on all compilers I have ever tried it on
  29. (even and especially K&R I).  I take this as a strong indication of
  30. conformance.  The switch construct above is explicitly disallowed, although
  31. there does not seem to be much difference in the expressions themselves.
  32.  
  33. I am of course aware that
  34.  
  35. switch (c - a) {
  36.     case 0: ...
  37.     case 1: ...
  38.     case 3: ...
  39.     default: ...
  40. }
  41.  
  42. is equivalent code, but it suffers from the division needed to evaluate
  43. c - a.
  44.  
  45. Konrad Schwarz
  46.